const { defaultEquals } = require('../util');
const { LinkedList } = require('./linked-list');
const { Node } = require('./models/linked-list-models');

class CircularLinkedList extends LinkedList {
  constructor(equalsFn = defaultEquals) {
    super(equalsFn);
  }

  insert(element, index) {
    if (index >= 0 && index <= this.count) {
      let current = this.head;
      const node = new Node(element);
      if (index === 0) {
        if (this.head == null) {
          this.head = node;
          node.next = this.head;
        } else {
          node.next = current;
          current = this.getElementAt(this.size() - 1);
          this.head = node;
          current.next = this.head;
        }
      } else {
        const previous = this.getElementAt(index - 1);
        node.next = previous.next;
        previous.next = node;
      }
      this.count++;
      return true;
    }
    return false;
  }

  removeAt(index) {
    if (index >= 0 && index < this.count) {
      let current = this.head; // current游标指向head元素
      // 是从第一个元素开始移除的
      if (index === 0) {
        // 如果只有一个元素
        if (this.size() === 1) {
          this.head = undefined; // 将head设置为undefined
        } else {
          // 有多个元素
          const removed = this.head; // removed指向要移除的元素
          this.head = current.next; // 将head元素指向下一个
          current = this.getElementAt(this.size() - 1); // 找到最后一个元素
          current.next = this.head; // 将最后一个元素指向head
          current = removed; // 将current游标指向要移除的元素
        }
      } else {
        const previous = this.getElementAt(index - 1); // 找到要移除元素的前一个元素
        current = previous.next; // 将current游标指向要移除的元素
        previous.next = current.next; // 将要移除的元素的前一个元素的next指向要移除元素的后一个元素
      }
      this.count--; // 数量减一
      return current.element; // return出要移除的元素 等待垃圾回收
    }
    return undefined;
  }
}

exports.CircularLinkedList = CircularLinkedList;
